<template>
<div class="subscribeAlarm-contanier">
    <div class="search-box">
        <div class="search-box-sub">
            <span class="lable-text">{{$t('equipmentType')}}</span>
              <el-select v-model="searchData.deviceType" filterable :placeholder="$t('pleaseSelect')" :clearable='true' @change="()=>{errorMsgList=[];searchData.alarmName=''}">
                  <el-option
                  v-for="item in deviceTypes"
                  :key="item.value"
                  :label="item.code"
                  :value="item.value">
                  </el-option>
              </el-select>
        </div>
        <div class="search-box-sub">
            <span class="lable-text">{{$t('alarm.errorMessage')}}</span>
            <!-- <el-input v-model="searchData.alarmName" clearable></el-input> -->
            <el-select
                v-model="searchData.alarmName"
                filterable
                clearable
                remote
                reserve-keyword
                :placeholder="$t('common.ple-insert-keyword')"
                :remote-method="getErrorMsg"
                :loading="loadingSelect">
                <el-option
                v-for="item in errorMsgList"
                :key="item"
                :label="item"
                :value="item">
                </el-option>
            </el-select>
        </div>
        <div class="search-box-sub">
          <el-button type="primary" @click='query' >{{$t('query')}}</el-button>
        </div>
        <div class="search-box-sub right">
          <el-button icon="el-icon-back" @click='()=>{this.$router.go(-1)}' >{{$t('back')}}</el-button>
        </div>
    </div>
    <div class="fix-box">
      <div class="item">
        <div class="sub_title">{{$t('device.inverter.js_no_subscription')}} <span>{{ ` (${dataRows1.length||0})` }}</span></div>
        <baseTable v-loading="loading1" row-key='sid' :data="dataRows1" border stripe @selection-change="handleSelectionChange1($event)" @row-click="handleSelectionChange1($event)"  :column='column1' :select="true" :height="500" ref="table1">
          <template #deviceType="{data}">
              <span>{{comm.returnCode(deviceTypes,data.deviceType)}}</span>
          </template>
        </baseTable>
      </div>
      <div class="middle">
        <p><el-button type="" icon="iconfont icon-right" @click="add">{{$t('Add')}}</el-button></p>
        <p><el-button type="" icon="iconfont icon-left" @click="remove">{{$t('Remove')}}</el-button></p>
      </div>
      <div class="item">
        <div class="sub_title">{{$t('Subscribed_items')}} <span>{{ ` (${dataRows2.length})` }}</span></div>
        <baseTable v-loading="loading2" row-key='sid' :data="dataRows2" border stripe @selection-change="handleSelectionChange2($event)"  @row-click="handleSelectionChange2($event)" :select="true" :height="500" :column='column2' ref="table2">
          <template #deviceType="{data}">
              <span>{{comm.returnCode(deviceTypes,data.deviceType)}}</span>
          </template>        
        </baseTable>
      </div>
    </div>
    <p class="pull-right">
      <el-button type="primary" @click="save">{{$t('save')}}</el-button>
      <el-button type="primary" @click="apply">{{$t('Apply')}}</el-button>
    </p>
</div>
</template>

<script>
import baseTable from '@/components/common/baseTable'
export default {
    components: {
      baseTable
    },
    props: {

    },
    data() {
        return {
          searchData:{
            deviceType:'',
            alarmName:''
          },
          errorMsgList:[],
          loadingSelect:false,
          loading1:false,
          loading2:false,
          column1:[
            {
            title:this.$t('equipmentType'),
            value:'deviceType',
            slot:'deviceType'
          },{
            title:this.$t('alarm.errorMessage'),
            value:'alarmName',
          },

          ],
          column2:[
            {
              title:this.$t('equipmentType'),
              value:'deviceType',
              slot:'deviceType'
            },{
              title:this.$t('alarm.errorMessage'),
              value:'alarmName',
            },
          ],
          dataRows1:[],
          dataRows2:[],
          middleRows:[],
          selectDatalist1:[],
          selectDatalist2:[],
          deviceTypes:[],
          alarmTypes:[]
        };
    },
    computed: {

    },
    watch: {

    },
    created() {

    },
    mounted() {
      this.getDictionaryBatch()
      this.devalarmsubGetSaveSetting()
      console.log(this.$refs,'ref')
    },
    methods: {
      async getErrorMsg(query){
          if(this.searchData.deviceType===''){
            this.$message.error(this.$t('Please_select_a_model'));
          }else{
            this.loadingSelect = true
            let res = await this.API.devalarmsubGetAlarmNameList({alarmName: query, deviceType: this.searchData.deviceType})
            this.errorMsgList=res || []
            this.loadingSelect = false
          }
      },
      async save(flag){
        console.log(this.dataRows2)
        let alarmIds = this.dataRows2.map(item => item.alarmIds)
        let res = await this.API.devalarmsubSave({
            alarmIds:alarmIds.join()
        })
        if(res.success){
          this.$message.success(this.$t('index.control_success'))
        }else{
          this.$message.error(this.$t('index.control_fail'))
        }
        console.log(flag,'flag----------')
      
        if(flag===true){
          this.devalarmsubGetSubList()
        }
        this.middleRows=[]
        this.devalarmsubGetSaveSetting()
      },
      async apply(){
        let alarmIds = this.dataRows2.map(item => item.alarmIds)
        let res = await this.API.devalarmsubSubmit({
            alarmIds:alarmIds,
            subId:new Date().getTime()
        })

        if(res.code===0){
            this.$message.success(this.$t('index.control_success'));
          }else if(res.code===1){
              this.$message.warning(this.$t('Try_again_later'));
          }else if(res.code===2){
              this.$message.error(this.$t('Program_exception'));
          }
        this.middleRows=[]
        this.devalarmsubGetSaveSetting()
      },
      add(){
        if(this.selectDatalist1.length>0){
          this.selectDatalist1.forEach(item =>{
            item.selectFlag=1
            this.middleRows.unshift(item)
          })
          this.dataRows1 = this.dataRows1.filter(item => item.selectFlag === 0)
          this.dataRows2.unshift(...this.selectDatalist1)
          this.toggleSelection(this.selectDatalist1,'table2')
        }else{
          this.$message.error(this.$t('pleaseSelect'))
        }
      },
      remove(){
        if(this.selectDatalist2.length>0){
          this.selectDatalist2.forEach(item =>{
            item.selectFlag=0
          })
          this.dataRows2 = this.dataRows2.filter(item => item.selectFlag === 1)
          this.dataRows1.unshift(...this.selectDatalist2)
          this.toggleSelection(this.selectDatalist2,'table1')
        }else{
          this.$message.error(this.$t('pleaseSelect'))
        }
      },
      query(){
        console.log(this.middleRows)
        
        if(this.searchData.deviceType==''){
          this.$message.error(this.$t('Please_select_a_model'));
        }else{
          if(this.middleRows.length>0){
            this.$confirm(this.$t('subscribed_items_before_msg'),  {
              confirmButtonText: this.$t('save'),
              cancelButtonText: this.$t('cancel'),
              type: 'warning'
            }).then(() => {
              this.save(true)
            }).catch(() => {
              this.middleRows=[]//取消暂存的中间项
              this.devalarmsubGetSaveSetting()
              this.devalarmsubGetSubList()
            });
          }else{
            this.devalarmsubGetSubList()
          }
        }
      },
      async getDictionaryBatch(){
          let res = await this.API.getDictionaryBatch({
              dictCodes:'ALARM_TYPES,INVERTER_TYPES',
              lang:localStorage.getItem('lang')||'zh_CN'
          })
          this.alarmTypes = res.ALARM_TYPES
          this.deviceTypes = res.INVERTER_TYPES
      },
      async devalarmsubGetSubList(){
        this.loading1 = true
        let res = await this.API.devalarmsubGetSubList(this.searchData)
        this.loading1= false
        this.dataRows1 = res.filter(item => item.selectFlag === 0)
      },
      async devalarmsubGetSaveSetting(){
        this.loading2 = true
        let res = await this.API.devalarmsubGetSaveSetting()
        this.loading2 = false
        this.dataRows2 = res
      },
      handleSelectionChange1(val){
        this.selectDatalist1=val
        console.log(this.selectDatalist1,'selectDatalist1')
      },
      handleSelectionChange2(val){
        this.selectDatalist2=val
        console.log(this.selectDatalist2,'selectDatalist2')
      },
      toggleSelection(rows,tableRef) {
        if (rows) {
          rows.forEach(row => {
            this.$refs[tableRef].$children[1].toggleRowSelection(row);
          });
        } else {
          this.$refs[tableRef].$children[1].clearSelection();
        }
      },
    },
};
</script>

<style lang="less">
.subscribeAlarm-contanier{
  .fix-box{
    // display: flex;
    .item{
      // flex: 1;
      float: left;
      width: calc(50% - 100px);
    }
    .middle{
      float: left;
      width: 200px;
      margin-top: 200px;
      width:200px;
      min-width:200px;
      text-align: center;
      button{
        width: 100px;
        margin-bottom: 20px;
      }
    }
  }
  .sub_title{
    margin-bottom: 10px;
    font-size: 14px;
    text-align: center;
    color: #555;
    font-weight: bold;
  }
  .baseTable-main-box .table-nav-box {
    display: none;
  }
}
</style>
